﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using Informant.Services.SmsMessaging;

namespace Informant.Services.Windows
{
	public partial class InformantWinService : ServiceBase
	{
		ServiceHost _smsServiceHost;
		ISmsService _smsService;

		/// <summary>
		/// Initializes a new instance of the <see cref="InformantWinService"/> class.
		/// </summary>
		public InformantWinService()
		{
			InitializeComponent();
		}

		/// <summary>
		/// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
		/// </summary>
		/// <param name="args">Data passed by the start command.</param>
		protected override void OnStart(string[] args)
		{
			_smsService = new SmsService();

			if (_smsServiceHost == null
				|| (_smsServiceHost.State != CommunicationState.Opened
					&& _smsServiceHost.State != CommunicationState.Opening))
			{
				_smsServiceHost = new ServiceHost(_smsService);
				_smsServiceHost.Open();
			}
		}

		/// <summary>
		/// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
		/// </summary>
		protected override void OnStop()
		{
			if (_smsServiceHost != null)
			{
				_smsServiceHost.Close();
				_smsServiceHost = null;
			}
			if (_smsService != null)
			{
				_smsService.Dispose();
				_smsService = null;
			}
		}
	}
}
